<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 使用栅格布局: 每行宽24格，gutter设置列距，span设置每列占多少格 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserVisible = !addUserVisible"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 表格组件，表格数据从data中获取，每列数据从prop中获取 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <!-- 通过模板标签solt-scope="scope"(作用域插槽) 获取到scope,然后通过scope.row获取到这一行的数据 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip
              effect="dark"
              content="编辑"
              placement="top"
              :enterable="false"
            >
              <el-button
                size="mini"
                type="primary"
                @click="showEditDialog(scope.row.id)"
                icon="el-icon-edit"
              ></el-button>
            </el-tooltip>

            <el-tooltip
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
            >
              <el-button
                size="mini"
                type="danger"
                @click="handleDeleteUser(scope.row.id, scope.row.username)"
                icon="el-icon-delete"
              ></el-button>
            </el-tooltip>
            <!-- el-tooltip文字提示 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                size="mini"
                type="warning"
                @click="showSetRoleDialog(scope.row)"
                icon="el-icon-setting"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addUserVisible"
      width="50%"
      @close="addUserDialogClosed"
    >
      <el-form
        :model="addUserForm"
        :rules="userFormRules"
        ref="addUserFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editUserVisible"
      width="50%"
      @close="$refs.editUserFormRef.resetFields()"
    >
      <el-form
        :model="editUserForm"
        :rules="userFormRules"
        ref="editUserFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限的对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleVisible" width="50%" @close="selectedRoleId = ''">
      <div>
        <p>当前用户: {{ userInfo.username }}</p>
        <p>当前角色: {{ userInfo.role_name }}</p>
        <p>
          分配新角色:
          <el-select v-model="selectedRoleId" clearable placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data() {
    // 验证邮箱的自定义规则
    /* var checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if(regEmail.test(value)){
        // 合法邮箱
        return callback()
      }
      callback(new Error('请输入一个合法的邮箱'))
    } */
    // 验证电话号码的自定义规则
    var checkMobile = (rule, value, callback) => {
      // 验证手机号码的正则表达式
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        // 合法邮箱
        return callback()
      }
      callback(new Error('请输入一个合法的手机号码'))
    }

    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5,
      },
      userList: [],
      total: 0,
      // 控制对话框的显示与隐藏
      addUserVisible: false,
      editUserVisible: false,
      setRoleVisible: false,
      // 添加用户的表单数据
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      editUserForm: {},
      // 添加用户表单数据的验证规则
      userFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名在3~10个字符之间',
            trigger: ['blur', 'change'],
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 16,
            message: '密码在6~16个字符之间',
            trigger: ['blur', 'change'],
          },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          // 可以使用自定义规则，也可以使用官方规则
          // { validator: checkEmail, trigger: ['blur', 'change'] }
          {
            type: 'email',
            message: '请输入合法的邮箱',
            trigger: ['blur', 'change'],
          },
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: ['blur', 'change'] },
        ],
      },
      // 需要分配角色的用户信息
      userInfo: {},
      // 保存角色信息
      roleList: [],
      // 新角色的id
      selectedRoleId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200)
        return this.$message.error('获取用户列表失败！！！')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      // 获取到新的 每页显示数量
      this.queryInfo.pagesize = newSize
      // 重新发送请求
      this.getUserList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      // 获取到新的 页码值
      this.queryInfo.pagenum = newPage
      // 重新发送请求
      this.getUserList()
    },
    // 监听 Switch 的状态变化
    async userStateChange(userInfo) {
      // 使用用户状态修改接口
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error(
          `${userInfo.username} 用户状态修改失败！！！`
        )
      }
      this.$message.success(`${userInfo.username} 用户状态修改成功！！！`)
    },
    addUserDialogClosed() {
      // 对话框关闭后，清空所有表单数据
      this.$refs.addUserFormRef.resetFields()
    },
    addUser() {
      // 先对表单进行预校验
      this.$refs.addUserFormRef.validate(async (vaild) => {
        if (!vaild) return
        // 调用接口api，添加用户
        const { data: res } = await this.$http.post('users', this.addUserForm)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        // 关闭对话框
        this.addUserVisible = false
        this.$message.success('添加用户成功')
        // 刷新表格
        this.getUserList()
      })
    },
    async showEditDialog(id) {
      this.editUserVisible = true
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error('查询信息失败')
      this.editUserForm = res.data
      this.editUserVisible = true
    },
    editUser() {
      this.$refs.editUserFormRef.validate(async (vaild) => {
        if (!vaild) return
        const { data: res } = await this.$http.put(
          'users/' + this.editUserForm.id,
          {
            email: this.editUserForm.email,
            mobile: this.editUserForm.mobile,
          }
        )
        if (res.meta.status !== 200)
          return this.$message.error('修改用户信息失败')
        // 关闭对话框
        this.editUserVisible = false
        this.$message.success('修改用户信息成功')
        // 刷新表格
        this.getUserList()
      })
    },
    handleDeleteUser(id, username) {
      // ！！！ 以下没有使用asyns和await简化promise方法
      this.$confirm(`此操作将永久删除该用户 ${username}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$http.delete('users/' + id).then(
            (response) => {
              if (response.status >= 200 || response < 300) {
                this.$message.success(`用户 ${username} 删除成功!`)
                this.getUserList()
              } else return
            },
            (error) => [this.$message.error(error.message)]
          )
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    async showSetRoleDialog(userInfo) {
      this.userInfo = userInfo
      // 在打开对话框之前，先获取所有角色信息
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200)
        return this.$message.error('获取角色列表失败')
      this.roleList = res.data
      this.setRoleVisible = true
    },
    async setRole() {
      if(!this.selectedRoleId){
        return this.$message.error('请选择角色')
      }
      const {data: ref} = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
      if(ref.meta.status !== 200){
        return this.$message.error('角色更新失败')
      }
      this.$message.success('角色更新成功')
      this.getUserList()
      this.setRoleVisible = false
    },
  },
}
</script>

<style lang="less" scoped>
.el-row {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
}
</style>